#include "NMPreHeader.h"
#include "NMBullet.h"
#include "NMActionMgr.h"

NMBullet::NMBullet(CCSpriteBatchNode* batch, NMBulletType type)
:_type(type)
,_speed(400)
,_speedAxis(CCPointZero)
,_destroied(false)
{
	FUNCTION_ENTER();

	if (type == bulletType_Normal)
	{
		_batchRect = CCRectMake(0,0,16,39);
		_power = 30;
	}
	else if (type == bulletType_Pierce)
	{
		_batchRect = CCRectMake(16,0,20,61);
		_power = 40;
	}
	else if (type == bulletType_Decelerate)
	{
		_batchRect = CCRectMake(36,0,26,68);
		_power = 50;
	}

	initWithBatchNode(batch, _batchRect);
	autorelease();

	FUNCTION_LEAVE();
}

NMBullet::~NMBullet(void)
{
	FUNCTION_ENTER();

	FUNCTION_LEAVE();
}

void NMBullet::setAngle(float angle)
{
	FUNCTION_ENTER();

	setRotation(angle);
	_speedAxis.x = _speed * sin(CC_DEGREES_TO_RADIANS(angle));
	_speedAxis.y = _speed * cos(CC_DEGREES_TO_RADIANS(angle));

	FUNCTION_LEAVE();
}

void NMBullet::update(ccTime dt)
{
	FUNCTION_ENTER();

	setPosition(ccpAdd(getPosition(), ccpMult(_speedAxis, dt)));

	FUNCTION_LEAVE();
}

bool NMBullet::isCanBeDestroy()
{
	FUNCTION_ENTER();

	CCPoint pos = getPosition();
	bool result = false;

	if (pos.x <= -50 || pos.x >= 320 || pos.y <= 0 || pos.y >= 580)
		result = true;

	FUNCTION_LEAVE();

	return result;
}

void NMBullet::destroy()
{
	FUNCTION_ENTER();

	_destroied = true;
	CCAction* action = 	CCSequence::actions(
		CCAnimate::actionWithAnimation(NMActionMgr::shared()->getAniBulletTarget(bulletType_Normal), false),
		CCCallFunc::actionWithTarget(this, callfunc_selector(NMBullet::_trueDestroy)),
		NULL);

	runAction(action);

	FUNCTION_LEAVE();
}

void NMBullet::_trueDestroy()
{
	FUNCTION_ENTER();

	stopAllActions();
	if (getParent())
		removeFromParentAndCleanup(true);

	FUNCTION_LEAVE();
}

CCRect NMBullet::getBoundingBox()
{
	FUNCTION_ENTER();

	CCPoint posSelf = getPosition();

	FUNCTION_LEAVE();

	return CCRectMake(posSelf.x, posSelf.y, _batchRect.size.width, _batchRect.size.height);
}
